package org.csu.web.servlets;

import org.csu.domain.Account;
import org.csu.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class MainServlet extends HttpServlet {
    private static final String VIEW_INCLUDEACCOUNT="/WEB-INF/jsp/account/EditAccountForm.jsp";
    private static final String ERROR_MESSAGE="/WEB-INF/jsp/common/Error.jsp";
    private String username = null;
    private String password;
    Account account =new Account();
    private static final String MAIN = "/WEB-INF/jsp/catalog/Main.jsp";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AccountService accountService = new AccountService();
        username = req.getParameter("username");
        password = req.getParameter("password");
        HttpSession session = req.getSession();
        if (username==null){
            req.getRequestDispatcher(MAIN).forward(req,resp);
        }
        else {
            if (accountService.getAccount(username, password) == null) {
                session.setAttribute("message", "Failed! Your uername or password is wrong");
                req.getRequestDispatcher(ERROR_MESSAGE).forward(req, resp);
            } else {
                account = accountService.getAccount(username, password);
                req.setAttribute("account", account);
                session.setAttribute("username",username);
                req.getRequestDispatcher(MAIN).forward(req, resp);
            }
        }
    }
}
